#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <malloc.h>

#include "armsdkerr.h"
#include "armsdkcmdregister.h"
#include "uartcmdregister.h"

cmdStrList_t guartCmdList;

INT4 uartCmdStrRegister(CHR *data_str)
{
    return add_cmdList(&guartCmdList, data_str);
}

INT4 uartMatchCmd(CHR **input, CHR **cmdArgs, INT4 *pi4ArgNum)
{
    INT4 i4Inc = 0;
    INT4 i4WordNum = 0;
    INT4 i4CmdNum = 0;
    CHR *pu1matchStr = NULL;
    cmdStrList_t *cur_cmdStr = &guartCmdList;

    if (cur_cmdStr->next == NULL)
    {
        return FAILURE;
    }

    while (cur_cmdStr != NULL)
    {
        for (i4WordNum = 0; input[i4WordNum] != NULL; i4WordNum ++)
        {
            if (cur_cmdStr->au1CmdStrPtr[i4WordNum] == NULL)
            {
                COMMAND_ERR();
            }
            pu1matchStr = strstr(cur_cmdStr->au1CmdStrPtr[i4WordNum], input[i4WordNum]);

            if (pu1matchStr)
            {
                if (strchr(cur_cmdStr->au1CmdStrPtr[i4WordNum], '{') || 
                    strchr(cur_cmdStr->au1CmdStrPtr[i4WordNum], '[') ||
                    strchr(cur_cmdStr->au1CmdStrPtr[i4WordNum], '('))
                {
                    MEMCPY(cmdArgs[*pi4ArgNum], input[i4WordNum], strlen(input[i4WordNum]));
                    *pi4ArgNum = *pi4ArgNum + 1;

                    /* ADTAG: add by xueda on 2025/6/17, 
                     * comment: 判断参数是否有二级参数*/
                    if (strstr(pu1matchStr, "STR"))
                    {
                        i4WordNum += 1;
                        if (input[i4WordNum] != NULL)
                        {
                            MEMCPY(cmdArgs[*pi4ArgNum], input[i4WordNum], strlen(input[i4WordNum]));
                            *pi4ArgNum = *pi4ArgNum + 1;
                        }
                        else
                        {
                            COMMAND_ERR();
                        }
                    }
                }

                pu1matchStr = NULL;
                continue;
            }
            else
            {
                if (MEMCMP(cur_cmdStr->au1CmdStrPtr[i4WordNum], "STR", 3) == 0)
                {
                    MEMCPY(cmdArgs[*pi4ArgNum], input[i4WordNum], strlen(input[i4WordNum]));
                    *pi4ArgNum = *pi4ArgNum + 1;
                    continue;
                }
                break;
            }
        }
        if (input[i4WordNum] == NULL)
        {
            return (i4CmdNum - 1);
        }

        if (cur_cmdStr->next != NULL)
        {
            for (i4Inc = 0; i4Inc < (*pi4ArgNum); i4Inc ++)
            {
                MEMSET(cmdArgs[i4Inc], 0, CMD_WORD_LEN);
            }

            *pi4ArgNum = 0;
            i4CmdNum ++;
            cur_cmdStr = cur_cmdStr->next;
        }
        else
        {
            return FAILURE;
        }
    }
}

